package com.vgooo.client.vchannel.album;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.assist.ViewScaleType;
import com.umeng.analytics.MobclickAgent;
import com.vgooo.bean.NewListInfo;
import com.vgooo.bean.Picture;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.ui.VGScrollView;
import com.vgooo.client.ui.ViewPagerAdapter;
import com.vgooo.client.vchannel.PingActivity;
import com.vgooo.client.vchannel.PingDetail;
import com.vgooo.util.BitmapUtils;
import com.vgooo.util.BitmapUtils.PictureLoadingThreadPool;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.SimpleLoading;
import com.vgooo.util.SimpleLoading.Progress;
import com.vgooo.util.Utils;

public class AlbumDetailActivity extends VGActivity {
	private static final String className = "AlbumDetailActivity";// 类名，调试程序用

	private TextView title,title2;// 图赏标题
	private TextView source;// 图赏来源
	private TextView time;// 图赏发表时间
	private TextView review;// 图赏查看次数

	private ViewPager pager;// 图赏大图详情
	private ViewPager pingPager;
	private ViewPagerAdapter adapter ;
	private View loading ;//
	private Bitmap bm ;
	private ImageView imageView ;
	
	private static Progress pro ;


	private TextView currentIndexTV;// 正在显示的图片索引

	private TextView allCountsTV;// 总图片数

	private int currentIndex;

	private int allCounts;

	private TextView pingButton;// 图赏评论数目

	private NewListInfo albumInfo;// 图赏信息
	private List<Picture> pictures;// 图片信息集合
	private List<String> urls ;
	
	private PictureLoadingThreadPool  albumLoadPool ;

	private PingDetail pingDetail ;
	
	private View content ,pingBottom ,titleVeiw;//,body ;
//	private TextView pingButton ;
	private VGScrollView scrollView ;
	
	private boolean isPingShow ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		needNewProgress = true ;
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		Bundle bundle = getIntent().getBundleExtra(NewListInfo.NEWS_TYPE_ALBUM);
		NewListInfo albumInfo = (NewListInfo) bundle.get(NewListInfo.NEWS_TYPE_ALBUM);
		
		if(null==albumInfo||albumInfo.equals(this.albumInfo)){
			detailVeiw.setVisibility(View.VISIBLE);
			return ;
		}else{
			this.albumInfo =albumInfo ;
		}
		
		
		detailVeiw = inflater.inflate(R.layout.album_detail, null);
		setContentView(detailVeiw);
		detailVeiw.setVisibility(View.INVISIBLE);
		initView();
		addListener();
		
		
		
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
		init() ;
		pro= SimpleLoading.startProgress( loading);
		//图片下载线程池
		albumLoadPool = new PictureLoadingThreadPool(context, 5);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
		if(null!=pingDetail&&pingDetail.isEdit){
			Utils.hideSoftInput(scrollView);
		}
		Utils.hideSoftInput(detailVeiw);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		pro.cancel();
		//清空线程池
		albumLoadPool.exit();
		super.onDestroy();
	}

	@Override
	public void initView() {
		// TODO Auto-generated method stub
		
		pingPager = (ViewPager) findViewById(R.id.album_ping_view_pager);
		
		title = (TextView) this.findViewById(R.id.album_detail_news_title);
		source = (TextView) this.findViewById(R.id.album_detail_news_source_tv);
		time = (TextView) this.findViewById(R.id.album_detail_news_time_tv);
		review = (TextView) this.findViewById(R.id.album_detail_news_review_tv);
		imageView = (ImageView) this.findViewById(R.id.album_detail_imageView);
		loading = this.findViewById(R.id.album_detail_loading_image);
		pager = (ViewPager) this.findViewById(R.id.album_detail_image);

		currentIndexTV = (TextView) this.findViewById(R.id.album_detail_current_index);
		allCountsTV = (TextView) this.findViewById(R.id.album_detail_all_counts);
		

		pingBottom = findViewById(R.id.album_detail_ping);
		pingButton = (TextView) findViewById(R.id.ping_bottom_layout_button);
		scrollView = (VGScrollView) findViewById(R.id.album_detail_news_body) ;
		pingDetail = new PingDetail(cparent, PingDetail.TYPE_ALBUM);
		pingDetail.initView( pingBottom);
	}


	@Override
	public void setupView() {
		// TODO Auto-generated method stub
		
		title.setText(albumInfo.news_title);
		source.setText(albumInfo.news_source);
		review.setText(albumInfo.news_views);
		 time.setText(albumInfo.news_time);

		//设置ViewPager的高度
		int imageWith = bm.getWidth();
		int imageHeight = bm.getHeight() ;
		int albumHeight = pager.getWidth()*imageHeight/imageWith ;
		log("w : " +imageWith +" h :"+imageHeight +" albumHeight :" + albumHeight);
		android.widget.RelativeLayout.LayoutParams params = new android.widget.RelativeLayout.LayoutParams(android.widget.RelativeLayout.LayoutParams.FILL_PARENT,albumHeight) ;
		imageView.setLayoutParams(params);
		pager.setLayoutParams(params);
		
		if(bm!=null&&!bm.isRecycled()){
			bm.recycle() ;
			bm = null ;
		}
		
		pager.setAdapter(new ViewAdapter(pager, currentIndexTV, urls));
		pager.setCurrentItem(1);
		allCountsTV.setText(urls.size()+"");
		
		titleVeiw = inflater.inflate(R.layout.album_detail_title, null);
		((TextView)titleVeiw.findViewById(R.id.album_detail_news_title)).setText(albumInfo.news_title) ;
		((TextView)titleVeiw.findViewById(R.id.album_detail_news_source_tv)).setText(albumInfo.news_source) ;
		((TextView)titleVeiw.findViewById(R.id.album_detail_news_time_tv)).setText(albumInfo.news_time) ;
		((TextView)titleVeiw.findViewById(R.id.album_detail_news_review_tv)).setText(albumInfo.news_views) ;
		
		pingDetail.setupView(albumInfo.news_ping, albumInfo.news_id, titleVeiw);
		
		
		detailVeiw.setVisibility(View.VISIBLE);
		pingPager.setAdapter(new PingViewAdapter(pingDetail, pingPager));
		pingPager.setCurrentItem(1);
		setPingView(isPingShow);
	}

	@Override
	public void addListener() {
		pingButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setPingView(!isPingShow);
			}
		});
		scrollView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(null!=pingDetail&&pingDetail.isEdit){
					Utils.hideSoftInput(scrollView);
				}
				return false;
			}
		});
	}


	@Override
	public void getData(){
		isPingShow = false ;
		try {
			
			String urlPath = HttpUtils.BASE_URI + "picturedetail?id="
					+ albumInfo.news_id;
			String jsonString = HttpUtils.getJsonString(urlPath);
			Map<String, Object> map = GSonTools.getObjectMaps(jsonString);

			albumInfo.news_source = (String) map.get("album_source");
			albumInfo.news_time = (String) map.get("album_time");
			List<Map<String, String>> list = (List<Map<String, String>>) map
					.get("pictures");
			pictures = new ArrayList<Picture>(list.size());
			urls = new ArrayList<String>() ;
			for (Map<String, String> m : list) {
				Picture p = new Picture();
				p.album_id = m.get("album_id");
				p.image_id = m.get("image_id");
				p.image_thumbnail = m.get("image_thumbnail");
				p.image_small_thumbnail = m.get("image_small_thumbnail");
				urls.add(p.image_thumbnail);
				pictures.add(p);
			}
			InputStream inputStream = null ;
			bm = BitmapFactory.decodeStream(HttpUtils.getInputStream(pictures.get(1).image_thumbnail));
			DebugTools.log(className, pictures.toString());
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e) ;
		}

	}

	
	private void setPingView(boolean isShowPing){
		if(isShowPing){
			scrollView.setVisibility(View.INVISIBLE);
			pingPager.setVisibility(View.VISIBLE);
			pingButton.setText("原文");
			Main.title.setText("评论详情");
		}else{
			scrollView.setVisibility(View.VISIBLE);
			pingPager.setVisibility(View.INVISIBLE);
			pingButton.setText("评论("+albumInfo.news_ping+")");
			Main.title.setText(ViewLayout.viwStack.peek().title);
		}
		this.isPingShow = isShowPing ;
	}
	@Override
	public void doClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		// TODO Auto-generated method stub
		switch (v.getId()) {


		default:
			if(pingDetail!=null){
				pingDetail.doClick(v);
			}else{
				DebugTools.log(className, "doClick() 未定义控件单击后的事件......" + v.getId());
			}
			break;
		}
	}
	
	
	private class ViewAdapter extends PagerAdapter implements OnLongClickListener ,OnClickListener,OnPageChangeListener{
		private List<View> views ;
		private List<String> urls ;
		private ViewPager pager ;
		private TextView currentIndex ;
		private Context context ;
		private int len ;
		private android.widget.FrameLayout.LayoutParams params = new android.widget.FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
		
		public ViewAdapter(ViewPager pager,TextView currentIndex,List<String> urls) {
			super();
			this.urls = urls;
			this.len = urls.size() ;
			this.context = pager.getContext() ;
			this.currentIndex = currentIndex ;
			this.pager = pager ;
			this.pager.setOnPageChangeListener(this);
			initView();
//			this.pager.setCurrentItem(1);
			log("ViewAdapter() len : " +len);
		}
		
		private void initView(){
			views = new ArrayList<View>() ;
			views.add(new ImageView(context));
			for(int i =0 ; i < len ;i++){
				ImageView iv = new ImageView(context);
				iv.setTag(i);
				iv.setLayoutParams(params);
				iv.setClickable(true);
				iv.setLongClickable(true);
				iv.setOnClickListener(this);
				iv.setOnLongClickListener(this);
				iv.setPadding(2, 0, 2, 0);
				iv.setScaleType(ScaleType.FIT_CENTER);
				views.add(iv);
			}
			views.add(new ImageView(context));
		}

		@Override
		public Object instantiateItem(View container, int position) {
			View iv = views.get(position);
			if(position > 0 &&position<=urls.size())
			BitmapUtils.albumLoadPool.LoadImage((ImageView)iv, urls.get(position-1));
			((ViewPager)container).addView(iv);
			return iv ;
		}
		
		@Override
		public void destroyItem(View container, int position, Object object) {
			// TODO Auto-generated method stub
			View iv = views.get(position);
			((ViewPager)container).removeView(iv);
			Bitmap bm = iv.getDrawingCache(true);
			if(position <= urls.size())
			((ImageView)iv).setImageResource(R.drawable.bg_transparent);
			if(bm!=null&&!bm.isRecycled()){
				bm.recycle() ;
				bm = null ;
				iv = null ;
			}
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return views.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0==arg1;
		}
		
		
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int i = (Integer) v.getTag();
			imageZoom(urls.get(i));
		}

		@Override
		public boolean onLongClick(View v) {
			// TODO Auto-generated method stub
			int i = (Integer) v.getTag();
			imageZoom(urls.get(i));
			return true;
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void onPageSelected(int position) {
			// TODO Auto-generated method stub
			if(null!=pingDetail&&pingDetail.isEdit){
				Utils.hideSoftInput(scrollView);
			}
			if(position==0){
				ViewLayout.setViewBack();
				pager.setCurrentItem(1);
			}
			if(position==views.size()-1){
				setPingView(true);
				pager.setCurrentItem(position-1);
				return ;
			}
			currentIndex.setText(position+"");
		}
		
	}
	
	private class PingViewAdapter extends PagerAdapter{

		private PingDetail ping ;
		private ViewPager pingPager ;
		private ArrayList<View> views ;
		
		
		public PingViewAdapter(PingDetail ping, final ViewPager pingPager) {
			super();
			this.ping = ping;
			this.pingPager = pingPager;
			initView();
			this.pingPager.setOnPageChangeListener(new OnPageChangeListener() {
				
				@Override
				public void onPageSelected(int arg0) {
					// TODO Auto-generated method stub
					switch (arg0) {
					case 0:
						setPingView(false);
						break;
					case 2:
						break ;
					default:
						break;
					}
					pingPager.setCurrentItem(1);
				}
				
				@Override
				public void onPageScrolled(int arg0, float arg1, int arg2) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onPageScrollStateChanged(int arg0) {
					// TODO Auto-generated method stub
				
				}
			});
		}
		private android.widget.FrameLayout.LayoutParams params = new android.widget.FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
		
		private void initView(){
			views = new ArrayList<View>() ;
			views.add(new ImageView(context));
			views.add(pingDetail.getmPullDownView());
		}
		
		
		
		@Override
		public void destroyItem(View container, int position, Object object) {
			// TODO Auto-generated method stub
			View view = this.views.get(position);
			((ViewPager)container).removeView(view);
		}

		@Override
		public Object instantiateItem(View container, int position) {
			View view = this.views.get(position);
			((ViewPager)container).addView(view);
			return view;
		}

		@Override
		public int getCount() {
			return this.views.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0==arg1;
		}
		
	}
	
//	private class MyListener implements OnLongClickListener ,OnClickListener{
//
//		@Override
//		public void onClick(View v) {
//			// TODO Auto-generated method stub
//			int i = (Integer) v.getTag();
//			imageZoom(urls.get(i));
//		}
//
//		@Override
//		public boolean onLongClick(View v) {
//			// TODO Auto-generated method stub
//			int i = (Integer) v.getTag();
//			imageZoom(urls.get(i));
//			return true;
//		}
//		
//	}
	
	private static void log(String info){
		Log.i("AlbumDetail", info) ;
	}
	
}
